import time
import base64
import pynput
import requests
import traceback
import subprocess
from PIL import Image, ImageGrab
from io import BytesIO
from gravityassist.bililib import get_headers

def open_image(path):
    if path.startswith('https://') or path.startswith('http://'):
        response = requests.get(path, headers=get_headers())
        image = Image.open(BytesIO(response.content))
    else:
        image = Image.open(path)
    return image

def encode_image_to_url(image: Image.Image, max_size: int = 256):
    with BytesIO() as buffer:
        if image.width * image.width > max_size * max_size:
            # calculate new width and height while maintaining aspect ratio
            if image.width > image.height:
                new_width = max_size
                new_height = int((image.height / image.width) * new_width)
            else:
                new_height = max_size
                new_width = int((image.width / image.height) * new_height)
            # resize image
            image = image.resize((new_width, new_height), Image.Resampling.BICUBIC)
        image = image.convert('RGB')
        image.save(buffer, format='jpeg')
        return 'data:image/jpeg;base64,' + base64.b64encode(buffer.getvalue()).decode()

def get_current_window_title():
    try:
        win_title = subprocess.check_output(['xdotool', 'getwindowfocus', 'getwindowname']).decode()
        return win_title.strip()
    except:
        traceback.print_exc()
        return ''

def get_current_window_bbox():
    try:
        result = subprocess.check_output([
            'xdotool', 'getwindowfocus', 'getwindowgeometry', '--shell',
        ]).decode()
        x = y = width = height = 0
        for line in result.splitlines():
            line = line.split('=')
            if len(line) == 2:
                if line[0] == 'X':
                    x = int(line[1])
                elif line[0] == 'Y':
                    y = int(line[1])
                elif line[0] == 'WIDTH':
                    width = int(line[1])
                elif line[0] == 'HEIGHT':
                    height = int(line[1])
        return x, y, x + width, y + height
    except:
        traceback.print_exc()
        return None

def get_current_window_image():
    kbd = None
    if get_current_window_title() == 'Chat App':
        kbd = pynput.keyboard.Controller()
        with kbd.pressed(pynput.keyboard.Key.alt):
            kbd.tap(pynput.keyboard.Key.tab)
        time.sleep(0.25)
    bbox = get_current_window_bbox()
    image = ImageGrab.grab(bbox=bbox)
    if kbd:
        with kbd.pressed(pynput.keyboard.Key.alt):
            kbd.tap(pynput.keyboard.Key.tab)
    return image
